package cn.hx.admin.schedule;

import cn.hx.admin.entity.JobLog;
import cn.hx.admin.entity.ScheduleTask;
import cn.hx.admin.entity.UserSign;
import cn.hx.admin.service.JobLogService;
import cn.hx.admin.service.UserSignService;
import cn.hx.admin.util.StaticMethodGetBean;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalTime;
import java.time.ZoneId;
import java.util.Date;


public class MyJob implements Job {

    LocalTime startTime1 = LocalTime.of(8, 30);

    LocalTime startTime2 = LocalTime.of(9, 0);

    LocalTime endTime1 = LocalTime.of(17, 0);

    LocalTime endTime2 = LocalTime.of(17, 30);

    private String start;
    private String end;
    private ScheduleTask scheduleTask;


    @Override
    public void execute(JobExecutionContext context) {

        JobDataMap dataMap = context.getJobDetail().getJobDataMap();
        start = dataMap.getString("start");
        end = dataMap.getString("end");
        scheduleTask = (ScheduleTask) dataMap.get("scheduleTask");
        String url = "http://47.93.32.193:9200/gyhat02/_search";
        String requestBody = "{\n" +
                "  \"size\": 0,\n" +
                "  \"query\": {\n" +
                "    \"range\": {\n" +
                "      \"date\": {\n" +
                "        \"gte\": \"" + start + "\", \"lte\": \"" + end + "\"\n" +
                "      }\n" +
                "    }\n" +
                "  }, \"aggs\": {\n" +
                "    \"user_ids\": {\n" +
                "      \"terms\": {\n" +
                "        \"field\": \"userId.keyword\",\n" +
                "        \"size\": 30\n" +
                "      },\n" +
                "       \"aggs\": {\n" +
                "        \"latest_hit\": {\n" +
                "          \"top_hits\": {\n" +
                "            \"size\": 1,\n" +
                "            \"sort\": [\n" +
                "              {\n" +
                "                \"date\": {\n" +
                "                  \"order\": \"desc\"\n" +
                "                }\n" +
                "              }]\n" +
                "          }\n" +
                "        }\n" +
                "      }\n" +
                "    }\n" +
                "  }\n" +
                "}";
        HttpHeaders headers = new HttpHeaders();
        headers.setBasicAuth("elastic", "123456");
        headers.add("Content-Type", "application/json");
        HttpEntity<String> entity = new HttpEntity<>(requestBody, headers);
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
        String jsonData = response.getBody();

        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode jsonNode = null;
        try {
            jsonNode = objectMapper.readTree(jsonData);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        JsonNode userIDs = jsonNode.get("aggregations").get("user_ids");

        JsonNode buckets = userIDs.get("buckets");
        System.out.println(buckets);
        for (JsonNode bucket : buckets) {
            JsonNode latestHit = bucket.get("latest_hit");
            JsonNode hitsNode = latestHit.get("hits");
            JsonNode sourceNode = hitsNode.get("hits").get(0).get("_source");
            UserSign userSign = new UserSign();
            JsonNode userId = sourceNode.get("userId");
            JsonNode date = sourceNode.get("date");
            userSign.setDeviceId(userId.toString().replaceAll("\"",""));
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            Date currentTime = null;
            System.err.println(start);
            try {
                currentTime = dateFormat.parse(date.toString().replaceAll("\"", ""));
                userSign.setSignTime(currentTime);
                // 将Date对象转换为LocalTime
                LocalTime localTime = currentTime.toInstant().atZone(ZoneId.systemDefault()).toLocalTime();
                // 判断当前时间是否在时间范围内
                if (localTime.isAfter(startTime1) && localTime.isBefore(endTime1)) {
                    userSign.setSignInfo(String.valueOf(3));
                } else if (localTime.isAfter(endTime1) && localTime.isBefore(startTime2)) {
                    userSign.setSignInfo(String.valueOf(1));
                } else if (localTime.isAfter(startTime2) && localTime.isBefore(endTime2)) {
                    userSign.setSignInfo(String.valueOf(0));
                }
                UserSignService bean = StaticMethodGetBean.getBean(UserSignService.class);
                bean.insert(userSign);
            } catch (Exception e) {
                JobLogService jobLogService = StaticMethodGetBean.getBean(JobLogService.class);
                JobLog jobLog = new JobLog();
                jobLog.setJobName(scheduleTask.getBeanName());
                jobLog.setJobGroup(scheduleTask.getMethodName());
                jobLog.setInvokeTarget(scheduleTask.getCronExpression());
                jobLog.setStatus(String.valueOf(scheduleTask.getStatus()));
                jobLog.setExceptionInfo(e.getMessage());
                jobLog.setJobMessage("定时任务执行失败！");
                jobLog.setCreateTime(new Date());
                jobLogService.insert(jobLog);
            }
        }
    }
}